#
# @lc app=leetcode.cn id=845 lang=python3
#
# [845] 数组中的最长山脉
#

# @lc code=start
from typing import List


class Solution:
    def longestMountain1(self, A: List[int]) -> int:
        left = middle = right = 0
        end = len(A)
        ret = 0
        while middle + 1 < end:
            if A[middle] < A[middle + 1]:
                middle += 1
                right = middle
            else:
                while right + 1 < end and A[right] > A[right + 1]:
                    right += 1

                if left < middle < right:
                    ret = max(right - left + 1, ret)

                if right + 1 < end and A[right] == A[right + 1]:
                    left = middle = right = right + 1
                else:
                    left = middle = right
        return ret

    def longestMountain(self, A: List[int]) -> int:
        left = right = 0
        n = len(A)
        ret = 0
        while left < n - 2:
            right = left + 1
            if A[left] < A[right]:
                while right < n - 1 and A[right] < A[right + 1]:
                    right += 1
                if right < n - 1 and A[right] > A[right + 1]:
                    while right < n -1 and A[right] > A[right + 1]:
                        right += 1
                    ret = max(ret, right - left + 1)
                else:
                    right += 1
            left = right        
        return ret


if __name__ == "__main__":
    s = Solution()
    t1 = [2, 1, 4, 7, 3, 2, 5]
    r1 = s.longestMountain(t1)
    print(r1, 5)

    t2 = [2, 2, 2]
    r2 = s.longestMountain(t2)
    print(r2, 0)

    print(s.longestMountain([3, 2]), 0)
    print(s.longestMountain([40, 51, 29, 19, 50, 25]), 4)

# @lc code=end
